package com.kgc.scd.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kgc.scd.bean.Address;
import com.kgc.scd.bean.Order;
import com.kgc.scd.bean.OrderVO;
import com.kgc.scd.config.GoodsLiuConfig;
import com.kgc.scd.config.KdApiEOrderDemo;
import com.kgc.scd.config.PersonInfo;
import com.kgc.scd.config.Sender;
import com.kgc.scd.service.OrderService;
import com.kgc.scd.util.HttpClient4Util;
import com.kgc.scd.util.PageSupport;
import com.kgc.scd.util.RequestResult;
import com.kgc.scd.util.ResultBuildUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Info;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created On : 2022/11/15.
 * <p>
 * Author : #jiangguoqiang
 * <p>
 * Description: OrderComtroller
 */
@RestController
@Slf4j
@Api(tags = "订单入口")
public class OrderComtroller {

    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsLiuConfig goodsLiuConfig;
    @Autowired
    private KdApiEOrderDemo kdApiEOrderDemo;

    /**
     *  快递下单发货
     */
    @PostMapping("/orderExpress")
    @ApiOperation(value = "快递下单发货",notes = "快递下单发货")
    public RequestResult<String> orderExpress(@ApiParam(name = "orderNo",value = "订单号")@RequestParam String orderNo) throws Exception {
        log.info("接收 的 订单号：{}",orderNo);
        /**
         *  创建请求链接
         */
        String expressUrl =goodsLiuConfig.getOrderExpressUrl();
        // 查询订单信息
        OrderVO orderVo = orderService.queryOrderByNo(orderNo);
        log.info("查询的订单信息：{}",orderVo);
        if (ObjectUtils.isEmpty(orderVo)){
            return ResultBuildUtil.fail("999","此订单还未支付");
        }
        // 请求参数
        Map<String,Object> RequestData = new HashMap<>();

        // 快递公司
        RequestData.put("ShipperCode",goodsLiuConfig.getShipperCode());
        RequestData.put("MonthCode",goodsLiuConfig.getMonthCode());
        RequestData.put("CustomerName",goodsLiuConfig.getCustomerName());
        RequestData.put("ExpType",goodsLiuConfig.getExpType()); //快递业务类型
        RequestData.put("PayType",goodsLiuConfig.getPayType()); //运费支付方式
        RequestData.put("orderCode",orderVo.getOrderId());
        /**
         *  发件人信息
         */
        Sender sender = goodsLiuConfig.getSender();
        RequestData.put("Sender",sender);
        RequestData.put("Quantity",1);
        //商品信息
        List<Map<String,String>> commodities = new ArrayList<>();
        Map<String,String> goodsMap = new HashMap<>();
        goodsMap.put("GoodsName",orderVo.getGoodsName());
        commodities.add(goodsMap);
        RequestData.put("Commodity",commodities);
        /**
         *  收件人信息
         *  private PersonInfo Receiver;
         */
        // 收货信息
        Address address = orderVo.getAddress();
        RequestData.put("Receiver", PersonInfo.builder().Name(address.getName())
                .ProvinceName("江苏省").CityName("南京市")
                .ExpAreaName("江宁区").Address(address.getAddress())
                .Tel(address.getMobile()).build());
        log.info("地址{}",address);
        log.info("应用级参数：{}",JSON.toJSONString(RequestData));
        // 组装系统参数
        Map<String, Object> paramMap = kdApiEOrderDemo.getParamMap(JSON.toJSONString(RequestData),"1007");
        log.info("最终参数：{}",paramMap);
        String response4PostByMap = HttpClient4Util.getResponse4PostByMap(expressUrl, paramMap, "utf-8");
        JSONObject jsonObject = JSON.parseObject(response4PostByMap);
        log.info("返回的参数：{}",jsonObject);
        if (Boolean.parseBoolean(jsonObject.get("Success").toString())){
            // 成功 插入快递号到订单中...
            orderService.insertExpressNo(orderNo,jsonObject.getJSONObject("Order").getString("LogisticCode"));
        }

        return ResultBuildUtil.success(jsonObject.getJSONObject("Order").getString("LogisticCode"));
    }

    /**
     * @author : Administrator
     * @date   : 2022/11/17
     * @param  : [LogisticCode, orderNo]
     * @return : com.kgc.scd.util.RequestResult<java.util.Map<java.lang.String,java.lang.Object>>
     * @description : 快递查询
     */
    @PostMapping("/selectExpress")
    @ApiOperation(value = "查询物流",notes = "物流状态")
    public RequestResult<Map<String,Object>> selectExpress(@ApiParam(name = "LogisticCode",value = "物流单号")@RequestParam String LogisticCode,
                                                           @ApiParam(name = "orderNo",value = "订单号")@RequestParam String orderNo) throws Exception {
        log.info("接收 的 订单号：{}",orderNo);
        String expressUrl =goodsLiuConfig.getOrderExpressUrl();
        // 请求参数
        Map<String,Object> RequestData = new HashMap<>();

        // 快递公司
        RequestData.put("ShipperCode",goodsLiuConfig.getShipperCode());
        RequestData.put("OrderCode",orderNo);
        RequestData.put("LogisticCode",LogisticCode);
        Map<String, Object> paramMap = kdApiEOrderDemo.getParamMap(JSON.toJSONString(RequestData),"1002");
        log.info("最终参数：{}",paramMap);
        String response4PostByMap = HttpClient4Util.getResponse4PostByMap(expressUrl, paramMap, "utf-8");
        Map<String,Object> map = JSON.parseObject(response4PostByMap, HashMap.class);
        return ResultBuildUtil.success(map);
    }
    /**
     * @author : Administrator
     * @date   : 2022/11/15
     * @param  : [comment, pageNo, pageSize]
     * @return : com.kgc.scd.util.RequestResult<?>
     * @description : 查询评论列表
     */
    @ApiOperation(value = "查询订单表",notes = "查询订单表")
    @GetMapping("/getOrderList")
    public PageSupport<Order> getCommentList(@ApiParam(name = "orderGoodsId",value = "订单状态") @RequestParam(required = false) String orderGoodsId,
                                             @ApiParam(required = true,name = "pageNo",value = "当前页") @RequestParam(value="pageNo",defaultValue="1") Integer pageNo,
                                             @ApiParam(required = true,name = "pageSize",value = "条数") @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize){

        if (Objects.isNull(pageNo) || pageNo < -1){
            pageNo = 1;
        }
        if (Objects.isNull(pageSize)){
            pageSize = -1;
        }
        return orderService.getOrderListAndPage(orderGoodsId, pageNo, pageSize);
    }

    @ApiOperation(value = "删除订单",notes = "根据订单状态删除订单")
    @GetMapping("/delOrderList")
    public RequestResult<?> delOrderList(String id){

        boolean delOrder = orderService.delOrderList(id);

        if (delOrder){
            return ResultBuildUtil.success("删除成功");
        }
        return ResultBuildUtil.fail("删除失败,此状态不是已收货订单");
    }

    @GetMapping("/signOrderList")
    @ApiOperation(value = "签收订单",notes = "根据订单id来签收订单，将订单状态改为6")
    public RequestResult<?> signOrderList(@RequestParam String id){
        boolean signStatus = orderService.updateStatusSign(id);
        if (signStatus){
            return ResultBuildUtil.success("签收成功");
        }
        return ResultBuildUtil.fail("签收失败,此状态不是已发货订单");
    }
}
